package de.tum.in.eist.poll.controller;

import java.util.LinkedList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.tum.in.eist.poll.client.EIST_POLL;
import de.tum.in.eist.poll.service.OnDataUpdate;
import de.tum.in.eist.poll.shared.Lecture;

/**
 * Fetches the lectures from server
 * @author sudi
 *
 */
class LectureFetchCallback implements AsyncCallback<List<Lecture>> {
	LectureController lectureController;
	OnDataUpdate<List<Lecture>> callback;
	
	LectureFetchCallback(LectureController lC, OnDataUpdate<List<Lecture>> cb) {
		lectureController = lC;
		callback = cb;
	}
	@Override
	public void onFailure(Throwable caught) {
		// TODO Auto-generated method stub
		Window.alert("Fail! could not fetch lectures");
	}

	@Override
	public void onSuccess(List<Lecture> result) {
		// TODO Auto-generated method stub
		lectureController.setLectures(result);
		if (callback != null)
			callback.onDataUpdate(result);
	}
}
/**
 * controls the Lecture fetch/update and sets curren active lecture
 * @author sudi
 *
 */
public class LectureController {
	UserController userController;
	List<Lecture> lectures = new LinkedList<Lecture>();
	int selectedLecture;
	
	public LectureController(UserController u) {
		userController = u;
		selectedLecture = -1;
	}
	
	/**
	 * set id of current lecture
	 * @param id
	 */
	public void setSelected(int id) {
		selectedLecture = id;
	}
	
	/**
	 * get selected lecture
	 * @return lecture or null if none is selected
	 */
	public Lecture getSelected() {
		if (lectures.size() <= selectedLecture || selectedLecture < 0)
			return null;
		return lectures.get(selectedLecture);
	}
	
	/**
	 * get id of selected lecture
	 * @return the lecture id
	 */
	public int getSelectedId() {
		return selectedLecture;
	}
	
	/**
	 * fetch lectures from server
	 * @param cb the callback that receives the lectures
	 */
	public void fetchLectures(OnDataUpdate<List<Lecture>> cb) {
		
		if (!userController.isLoggedIn())
			return;
		
		EIST_POLL.getService().requestLectures(userController.getUser(), new LectureFetchCallback(this, cb));
	}
	
	/**
	 * get all lectures of the current user
	 * @return the lectures
	 */
	public List<Lecture> getLectures() {
		return lectures;
	}
	
	/**
	 * set lectures
	 * @param l the lectures
	 */
	public void setLectures(List<Lecture> l) {
		lectures = l;
		selectedLecture = -1;
	}
	
	/**
	 * get the usercontroller of the current session
	 * @return the UserController
	 */
	public UserController getUserController() {
		return userController;
	}
}
